import { useEffect, useRef } from "react";
import { useNavigationType, Outlet, NavigationType } from "react-router-dom";
import KeepAlive from "react-activation";

import NavBar from "./components/NavBar";

let preNavigateType: NavigationType | "PUSH" = "PUSH";
export default function App() {
  const navigateType = useNavigationType();
  const nodeRef = useRef<HTMLDivElement>(null);
  const fullPath = `${location.pathname}${location.search}`;

  // 每次路由变化时执行的逻辑
  useEffect(() => {
    const type = `${preNavigateType}_${navigateType}`;
    if (type === "POP_PUSH") {
      (nodeRef.current as HTMLDivElement).className = "slide-left";
      setTimeout(() => {
        (nodeRef.current as HTMLDivElement).className = "";
      }, 400);
    }
    preNavigateType = navigateType;
  }, [navigateType]);

  return (
    <>
      <div ref={nodeRef}>
        <KeepAlive id={fullPath} saveScrollPosition="screen" name={fullPath}>
          <NavBar refIns={nodeRef} title="首页" />
          <Outlet></Outlet>
        </KeepAlive>
      </div>
    </>
  );
}
